/** 
 * @copyright		all rights reserved.
 * @author			how_fly@yahoo.com
 * @brief			user can truncate all the schemas
 * 
 * @version			1.0
 * @date
 * 
 * 
 */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <mysql.h>

#include "truncate_all_db.h"
/**
 *  @brief truncate all the tables in one schema
 *  @param [in]MYSQL: the connection to mysql
 *  @param [in]const char* table: the name of table will be deleted. 
 *  @return int: 0 is good, -1 is error.
 */ 
int truncate_db(MYSQL& mysql,const char* table)
{
	char sql[2048] = {0};
	for(int i = 0; i <512; i++) ///there are 512 table in each schema
	{
		sprintf(sql, table, i);
		if( mysql_real_query(&mysql, sql, strlen(sql)) )
		{
			printf("error %s %d:%s\n",table,mysql_errno(&mysql),mysql_error(&mysql));
			continue;
		}	
	}
	return 0;
}

/**
 *  @brief truncate all the tables in one schema
 *  @param [in]MYSQL: the connection to mysql
 *  @param [in]conf_schema:the configure of schema
 *  @param [in]const char* table: the name of table will be initialized. 
 *  @return int: 0 is good, -1 is error.
 */ 
int truncate_schema_table(MYSQL& mysql, const conf_schema& _conf_schema, const char* table)
{
	mysql_init(&mysql);

	if(!mysql_real_connect(&mysql,  
		_conf_schema.host.c_str(),
		_conf_schema.user.c_str(),
		_conf_schema.password.c_str(),
		_conf_schema.name.c_str(),
		 0, NULL, 0))
	{
		printf("error, connect \n");
		return -1;
	}
	if(truncate_db(mysql, table) != 0)
	{
		mysql_close(&mysql);
		return -1;
	}
	printf("delete %s is ok\n",table);
	mysql_close(&mysql);
	return 0;
}
int truncate_all_db(const configure& conf)
{
	MYSQL mysql;

	///truncate keyword schema
	char keyword_table[] = "truncate TABLE KEYWORD_%03d"; 
	truncate_schema_table(mysql, conf.keyword, keyword_table);
	
	///truncate url schema
	char url_table[] = "truncate TABLE URL_%03d"; 
	truncate_schema_table(mysql, conf.url, url_table);
	
	///truncate pending schema
	char pending_table[] = "truncate TABLE PENDING_%03d";
	truncate_schema_table(mysql, conf.pending, pending_table);
			
	///truncate invalid schema	
	char invalid_table[] = "truncate TABLE INVALID_%03d";
	truncate_schema_table(mysql, conf.invalid, invalid_table);
		
	///truncate dict schema	
	char dict_table[] = "truncate TABLE DICT_%03d";
	truncate_schema_table(mysql, conf.dict, dict_table);
		
		
	return 0;
}
